package com.demo.controller;


import com.demo.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {


    @Autowired
    private RedisTokenStore redisTokenStore;


    //获取用户信息接口
    @RequestMapping("getUserInfo")
    public Result getUserInfo(Authentication authentication){

        return new Result(200,authentication,"获取用户信息成功");

    }


    //用户退出登录接口
    @RequestMapping("/logout")
    public Result logout(@RequestHeader("authorization") String authorization){


        if (!StringUtils.isEmpty(authorization)){

            String access_token = authorization.toLowerCase().replace("bearer ", "");
            //根据访问令牌获取token信息
            OAuth2AccessToken token = redisTokenStore.readAccessToken(access_token);


            if (token!=null){
                //根据token信息删除redis中的数据
                redisTokenStore.removeAccessToken(token);
                OAuth2RefreshToken refreshToken = token.getRefreshToken();
                redisTokenStore.removeRefreshToken(refreshToken);
            }

        }
        return new Result(200,null,"退出成功");

    }

}
